package server;

import java.net.*;
import java.io.*;

/** A starting point for network servers. */
public abstract class NetworkServer {
	private int port;

	/**
	 * Build a server on specified port. It will continue to accept connections,
	 * passing each to handleConnection until the server is killed (e.g.,
	 * Control-C in the startup window) or System.exit() from handleConnection
	 * of elsewhere in the Java code).
	 */
	public NetworkServer(int port) {
		this.port = port;
	}

	/**
	 * Monitor a port for connections. Each time one is established, pass
	 * resulting Socket to handleConnection.
	 */
	public void listen() {
		try {
			ServerSocket listener = new ServerSocket(port);
			Socket socket;
			while (true) { // Run until killed
				socket = listener.accept();
				handleConnection(socket);
			}
		} catch (IOException ioe) {
			System.out.println("IOException: " + ioe);
			ioe.printStackTrace();
		}
	}

	/**
	 * This is the method that provides the behavior to the server, since it
	 * determines what is done with the resulting socket. <B>Override this
	 * method in servers you write.</B>
	 */
	protected abstract void handleConnection(Socket socket) throws IOException;

	/** Gets port on which server is listening. */
	public int getPort() {
		return (port);
	}

}
